<template>
  <div class="dashboard-container">
    <div class="dashboard-header">
      <h1 class="dashboard-title">欢迎访问后台管理中心</h1>
      <div class="date-range-picker">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
          :clearable="true"
          :shortcuts="dateShortcuts"
        />
      </div>
    </div>

    <el-row :gutter="20" class="stat-row">
      <el-col :xs="24" :sm="12" :md="6" v-for="(stat, index) in stats" :key="index">
        <div :class="['stat-card', stat.class]">
          <div class="stat-icon">
            <component :is="stat.icon" />
          </div>
          <div class="stat-content">
            <div class="stat-title">{{ stat.title }}</div>
            <div class="stat-value">{{ formatNumber(stat.value) }}</div>
            <div class="stat-trend" v-if="stat.trend">
              <span :class="['trend-value', stat.trend > 0 ? 'up' : 'down']">
                <component :is="stat.trend > 0 ? 'ArrowUp' : 'ArrowDown'" class="trend-icon" />
                {{ Math.abs(stat.trend) }}%
              </span>
              <span class="trend-period">较上月</span>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :md="12">
        <div class="chart-container">
          <h2 class="chart-title">用户增加趋势</h2>
          <v-chart class="chart" :option="userGrowthChart" autoresize />
        </div>
      </el-col>
      <el-col :xs="24" :md="12">
        <div class="chart-container">
          <h2 class="chart-title">帖子发布趋势</h2>
          <v-chart class="chart" :option="postTrendChart" autoresize />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { User, Document, ChatDotRound, Star, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import network from '../../api/index'
const { request, common } = network

// 日期范围
const dateRange = ref([]);

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

// Register ECharts components
use([
  CanvasRenderer,
  LineChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const stats = ref([
  { title: '总用户', value: 0, icon: User, class: 'user-card', trend: 12 },
  { title: '所有帖子', value: 0, icon: Document, class: 'post-card', trend: 8 },
  { title: '总评论', value: 0, icon: ChatDotRound, class: 'comment-card', trend: -3 },
  { title: '所有点赞', value: 0, icon: Star, class: 'like-card', trend: 15 },
])

const userGrowthChart = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    },
    formatter: '{b}<br />{a}: {c}'
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '8%',
    top: '8%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLine: {
      lineStyle: {
        color: '#999'
      }
    },
    axisLabel: {
      color: '#666',
      rotate: 0,
      interval: 'auto',
      formatter: function(value) {
        // 如果日期太长，只显示月和日
        if (value.length > 8) {
          const parts = value.split('-');
          if (parts.length === 3) {
            return parts[1] + '-' + parts[2];
          }
        }
        return value;
      }
    }
  },
  yAxis: {
    type: 'value',
    axisLine: {
      lineStyle: {
        color: '#999'
      }
    },
    axisLabel: {
      color: '#666'
    },
    splitLine: {
      lineStyle: {
        type: 'dashed',
        color: '#eee'
      }
    }
  },
  series: [
    {
      name: '新增用户',
      data: [],
      type: 'line',
      smooth: true,
      lineStyle: {
        color: '#10b981',
        width: 4
      },
      itemStyle: {
        color: '#10b981'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(16, 185, 129, 0.4)'
          }, {
            offset: 1, color: 'rgba(16, 185, 129, 0.1)'
          }]
        }
      }
    }
  ]
})

const postTrendChart = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    },
    formatter: '{b}<br />{a}: {c}'
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '8%',
    top: '8%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLine: {
      lineStyle: {
        color: '#999'
      }
    },
    axisLabel: {
      color: '#666',
      rotate: 0,
      interval: 'auto',
      formatter: function(value) {
        // 如果日期太长，只显示月和日
        if (value.length > 8) {
          const parts = value.split('-');
          if (parts.length === 3) {
            return parts[1] + '-' + parts[2];
          }
        }
        return value;
      }
    }
  },
  yAxis: {
    type: 'value',
    axisLine: {
      lineStyle: {
        color: '#999'
      }
    },
    axisLabel: {
      color: '#666'
    },
    splitLine: {
      lineStyle: {
        type: 'dashed',
        color: '#eee'
      }
    }
  },
  series: [
    {
      name: '发布帖子',
      data: [],
      type: 'bar',
      itemStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: '#3b82f6'
          }, {
            offset: 1, color: '#60a5fa'
          }]
        },
        borderRadius: [4, 4, 0, 0]
      }
    }
  ]
})

const formatNumber = (num) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const { data } = await request(common.getStatistics, {}, 'GET');
    if (data) {
      stats.value[0].value = data.user_count; // 用户数量
      stats.value[1].value = data.post_count; // 帖子数量
      stats.value[2].value = data.comment_count; // 评论数量
      stats.value[3].value = data.like_count; // 点赞数量
    }
  } catch (error) {
    console.error('获取统计数据失败:', error);
  }
};

// 获取用户注册趋势
const fetchUserGrowthTrend = async () => {
  try {
    const params = {};
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dateRange.value[0];
      params.endDate = dateRange.value[1];
    }
    
    const { data } = await request(common.getUserGrowthTrend, params, 'GET');
    if (data) {
      userGrowthChart.value.xAxis.data = data.labels;
      userGrowthChart.value.series[0].data = data.data;
    }
  } catch (error) {
    console.error('获取用户注册趋势失败:', error);
  }
};

// 获取帖子发布趋势
const fetchPostPublishTrend = async () => {
  try {
    const params = {};
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dateRange.value[0];
      params.endDate = dateRange.value[1];
    }
    
    const { data } = await request(common.getPostPublishTrend, params, 'GET');
    if (data) {
      postTrendChart.value.xAxis.data = data.labels;
      postTrendChart.value.series[0].data = data.data;
    }
  } catch (error) {
    console.error('获取帖子发布趋势失败:', error);
  }
};

// 日期范围变化时重新获取数据
const handleDateChange = () => {
  fetchUserGrowthTrend();
  fetchPostPublishTrend();
};

onMounted(async () => {
  await fetchStatistics(); // 获取统计数据
  await fetchUserGrowthTrend(); // 获取用户注册趋势
  await fetchPostPublishTrend(); // 获取帖子发布趋势
});
</script>

<style scoped lang="scss">
.dashboard-container {
  margin: 0 auto;
  padding: 24px;
  border-radius: 16px;
  background-color: #f8fafc;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.dashboard-title {
  font-size: 28px;
  font-weight: 700;
  color: #1e293b;
  margin: 0;
  background: linear-gradient(135deg, #1e293b, #475569);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.date-range-picker {
  :deep(.el-range-editor) {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    border: 1px solid #e2e8f0;
    
    &:hover, &:focus {
      border-color: #3b82f6;
    }
    
    .el-range-input {
      color: #1e293b;
    }
    
    .el-range-separator {
      color: #64748b;
    }
  }
}

.stat-row {
  margin-bottom: 30px;
}

.stat-card {
  position: relative;
  overflow: hidden;
  border: none;
  border-radius: 16px;
  color: white;
  transition: all 0.3s ease;
  padding: 24px;
  height: 160px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  }

  .stat-icon {
    position: absolute;
    top: 20px;
    right: 20px;
    font-size: 48px;
    opacity: 0.2;
    
    svg {
      width: 48px;
      height: 48px;
    }
  }

  .stat-content {
    position: relative;
    z-index: 1;
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .stat-title {
    font-size: 18px;
    font-weight: 500;
    opacity: 0.9;
  }

  .stat-value {
    font-size: 36px;
    font-weight: 700;
    letter-spacing: -0.5px;
    margin-top: 4px;
  }
  
  .stat-trend {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-top: 8px;
    font-size: 14px;
    
    .trend-value {
      display: flex;
      align-items: center;
      gap: 4px;
      font-weight: 600;
      padding: 4px 8px;
      border-radius: 20px;
      
      &.up {
        background-color: rgba(255, 255, 255, 0.2);
      }
      
      &.down {
        background-color: rgba(255, 255, 255, 0.2);
      }
      
      .trend-icon {
        width: 14px;
        height: 14px;
      }
    }
    
    .trend-period {
      opacity: 0.8;
    }
  }
}

.user-card {
  background: linear-gradient(135deg, #10b981, #34d399);
  
  &::before {
    content: '';
    position: absolute;
    top: -50px;
    right: -50px;
    width: 150px;
    height: 150px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
  }
  
  &::after {
    content: '';
    position: absolute;
    bottom: -60px;
    left: -60px;
    width: 120px;
    height: 120px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
  }
}

.post-card {
  background: linear-gradient(135deg, #3b82f6, #60a5fa);
  
  &::before {
    content: '';
    position: absolute;
    top: -50px;
    right: -50px;
    width: 150px;
    height: 150px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
  }
  
  &::after {
    content: '';
    position: absolute;
    bottom: -60px;
    left: -60px;
    width: 120px;
    height: 120px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
  }
}

.comment-card {
  background: linear-gradient(135deg, #f59e0b, #fbbf24);
  
  &::before {
    content: '';
    position: absolute;
    top: -50px;
    right: -50px;
    width: 150px;
    height: 150px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
  }
  
  &::after {
    content: '';
    position: absolute;
    bottom: -60px;
    left: -60px;
    width: 120px;
    height: 120px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
  }
}

.like-card {
  background: linear-gradient(135deg, #ef4444, #f87171);
  
  &::before {
    content: '';
    position: absolute;
    top: -50px;
    right: -50px;
    width: 150px;
    height: 150px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
  }
  
  &::after {
    content: '';
    position: absolute;
    bottom: -60px;
    left: -60px;
    width: 120px;
    height: 120px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
  }
}

.chart-row {
  margin-top: 30px;
}

.chart-container {
  background-color: #ffffff;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  height: 100%;

  &:hover {
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
  }
}

.chart-title {
  font-size: 20px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 20px;
  text-align: center;
  position: relative;
  
  &::after {
    content: '';
    position: absolute;
    bottom: -8px;
    left: 50%;
    transform: translateX(-50%);
    width: 40px;
    height: 3px;
    background: linear-gradient(to right, #3b82f6, #60a5fa);
    border-radius: 3px;
  }
}

.chart {
  height: 350px;
}

@media (max-width: 768px) {
  .dashboard-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .dashboard-title {
    font-size: 24px;
  }
  
  .date-range-picker {
    width: 100%;
    
    :deep(.el-range-editor) {
      width: 100%;
    }
  }

  .stat-row {
    .el-col {
      margin-bottom: 20px;
    }
  }

  .chart-row {
    .el-col {
      margin-bottom: 20px;
    }
  }

  .stat-card {
    height: 140px;
    padding: 20px;

    .stat-icon {
      font-size: 36px;
      
      svg {
        width: 36px;
        height: 36px;
      }
    }

    .stat-title {
      font-size: 16px;
    }

    .stat-value {
      font-size: 28px;
    }
  }

  .chart-title {
    font-size: 18px;
  }

  .chart {
    height: 300px;
  }
}
</style>

